package com.caipu.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caipu.common.Result;
import com.caipu.entity.Category;
import com.caipu.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/admin/category")
@CrossOrigin
public class AdminCategoryController {
    
    @Autowired
    private CategoryService categoryService;
    
    @GetMapping("/list")
    public Result<Page<Category>> list(@RequestParam(defaultValue = "1") Integer page,
                                      @RequestParam(defaultValue = "10") Integer size,
                                      @RequestParam(required = false) String keyword) {
        Page<Category> pageObj = new Page<>(page, size);
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like("name", keyword);
        }
        
        queryWrapper.orderByDesc("create_time");
        Page<Category> result = categoryService.page(pageObj, queryWrapper);
        return Result.success(result);
    }
    
    @GetMapping("/all")
    public Result<List<Category>> all() {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("create_time");
        List<Category> list = categoryService.list(queryWrapper);
        return Result.success(list);
    }
    
    @GetMapping("/{id}")
    public Result<Category> getById(@PathVariable Long id) {
        Category category = categoryService.getById(id);
        return Result.success(category);
    }
    
    @PostMapping
    public Result<Void> save(@RequestBody Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setDeleted(0);
        
        boolean success = categoryService.save(category);
        return success ? Result.success() : Result.error("保存失败");
    }
    
    @PutMapping("/{id}")
    public Result<Void> update(@PathVariable Long id, @RequestBody Category category) {
        category.setId(id);
        category.setUpdateTime(LocalDateTime.now());
        
        boolean success = categoryService.updateById(category);
        return success ? Result.success() : Result.error("更新失败");
    }
    
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        boolean success = categoryService.removeById(id);
        return success ? Result.success() : Result.error("删除失败");
    }
}